<template>
  <el-dialog v-model="dialogVisible" title="用户登录" width="400px" :close-on-click-modal="false">
    <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input 
          v-model="loginForm.username" 
          placeholder="请输入用户名"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input 
          v-model="loginForm.password" 
          type="password" 
          placeholder="请输入密码"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <div class="login-footer">
          <el-link type="primary" @click="handleForgot">忘记密码?</el-link>
          <el-link type="primary" @click="handleRegister">没有账号？去注册</el-link>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleLogin">登录</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'register', 'forgot'])

const userStore = useUserStore()
const dialogVisible = ref(props.modelValue)
const loading = ref(false)
const loginFormRef = ref()

const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 清空表单的方法
const resetForm = () => {
  loginForm.value = {
    username: '',
    password: ''
  }
  loginFormRef.value?.resetFields()
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

const handleLogin = async () => {
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.loginAction(loginForm.value)
        ElMessage.success('登录成功')
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error('登录失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }
  })
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleRegister = () => {
  dialogVisible.value = false
  emit('register')
}

const handleForgot = () => {
  dialogVisible.value = false
  emit('forgot')
}
</script>

<style scoped>
.login-footer {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
</style>